package com.tom.joke;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

/**
 * Added by Tom on 2024/07/03.
 * 守护进程，双进程通讯
 */
public class GuardService extends Service {
    public static final int GuardID = 1; // 守护者id

    private ServiceConnection mServiceConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 连接上
            Log.d("TAG", "GuardService -- onServiceConnected");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("TAG", "GuardService -- onServiceDisconnected");
            // 断开连接, 重新启动，重新绑定
            startService(new Intent(GuardService.this, MessageService.class));
            bindService(new Intent(GuardService.this, MessageService.class), mServiceConn, Context.BIND_IMPORTANT);
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 创建通知频道
            NotificationChannel channel = new NotificationChannel("channel_id", "channel_name", NotificationManager.IMPORTANCE_DEFAULT);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
        // 创建通知并设置前台服务
        Notification notification = new NotificationCompat.Builder(this, "channel_id")
                .setContentTitle("My Service")
                .setContentText("Service is running in foreground")
                .build();
        // 提高进程的优先级, 提高到前台进程
        startForeground(GuardID, notification);

        // 绑定建立连接
        bindService(new Intent(this, MessageService.class), mServiceConn, Context.BIND_IMPORTANT);
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        // 返回Binder 驱动
        return new ProcessConnection.Stub() {};
//        return new ProcessConnection.Stub() {
//            @Override
//            public IBinder asBinder() {
//                return super.asBinder();
//            }
//        };
    }

}
